import { useEffect, useRef } from 'react';
import _ from 'lodash';

const map = new WeakMap();

const ob = new ResizeObserver((entries) => {
  entries.forEach((entrie) => {
    map.get(entrie.target)({
      width: entrie.borderBoxSize[0].inlineSize,
      height: entrie.borderBoxSize[0].blockSize,
      contentHeight: entrie.contentBoxSize[0].blockSize,
      contentWidth: entrie.contentBoxSize[0].inlineSize,
      target: entrie.target
    });
  });
});

type ResizeObserverCallback = (ResizeObserverOptions: {
  width: number;
  height: number;
  contentHeight: number;
  contentWidth: number;
  target: Element;
}) => void;

export default <T = HTMLElement>(resizeCallback: ResizeObserverCallback) => {
  const elRef = useRef<T>(null);
  const callbackRef = useRef(resizeCallback);

  useEffect(() => {
    const el = elRef.current! as unknown as HTMLElement;
    map.set(
      el,
      _.throttle<ResizeObserverCallback>((...args) => callbackRef.current(...args), 10)
    );
    ob.observe(el);
    return () => {
      ob.unobserve(el);
    };
  }, []);

  return [elRef];
};
